import React, { useEffect, useState } from 'react'
import { Table, Switch, Space, Button, Modal, Form, Input, Select } from 'antd';
import {
  DeleteOutlined,
  ExclamationCircleOutlined
 } from '@ant-design/icons';
import axios from 'axios';

const { Option } = Select;
const { confirm } = Modal;

export default function Userlist() {
  const ref = React.createRef();
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState([]); //用户数据
  const [roleList, setRoleList] = useState([]);  //角色列表
  const [regionList, setRegionList] = useState([]);  //地区列表
  const [visible, setVisible] = useState(false); //弹窗是否显示
  const [isDisabled, setIsDisabled] = useState(false);
  const { region, role:{ id }} = JSON.parse(localStorage.getItem('token'));
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '角色名称',
      dataIndex: 'roleId',
      render:(roleId)=>{
        switch(roleId){
          case 1:
            return '超级管理员';
          case 2:
            return '区域管理员';
          default:
            return '区域编辑';
        }
      }
    },
    {
      title: '区域',
      dataIndex: 'region',
      filters: [
        ...regionList.map(item => {
          return {
            text: item.title,   //界面显示的字段
            value:item.value    //对应的值
          }
        }),
        {
          text: '全球',
          value: '全球',
        }
      ],
      onFilter:(value, item) =>{
        if(value === '全球')
          return item.region === ''
        else
          return item.region === value
      },
      render:(region)=>{
        if(region === ''){
          return "全球";
        }
        else
          return region;
      }
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render:(roleState,item)=>{
        return (
          <Switch checkedChildren="开启" unCheckedChildren="关闭" 
           checked={roleState} 
           disabled={item.default}
           onChange={()=>{
            handleChange(item);
           }}
          />
        )
      }
    },
    {
      title: '操作',
      render:(_,item)=>{
        return(
          <Space size="middle">
            <Button 
              danger 
              shape="circle" 
              icon={<DeleteOutlined />} 
              size='small' 
              disabled={item.default}
              onClick={()=>{
                showConfirm(item)
              }}
            />
          </Space>
        )
      }
    }
  ];
  useEffect(()=>{
    axios({
      url:'/users'
    }).then(res =>{
      setDataSource(res.data);
    })
  },[])

  useEffect(()=>{
    axios({
      url:'/roles'
    }).then(res =>{
      setRoleList(res.data);
    })
  },[])

  useEffect(()=>{
    axios({
      url:'/regions'
    }).then(res =>{
      setRegionList(res.data);
    })
  },[])

  const filterdatasourece = (datasource) => {
    if(id === 1){
      return datasource;
    }
    else 
      var list = datasource.filter(item => 
        item.region === region && item.roleId === 3
    )
      return list;
  }

  const onCreate = (values) => {
    getData(values);
    setVisible(false);
  };

  const getData = (values) => {
    axios.post('/users',{...values, roleState:true, default:false}).then(res=>{
      setDataSource([...dataSource, res.data])
    })
  }

  const deleteuser = (id) => {
    let list = dataSource.filter(data => 
      data.id !== id);
      setDataSource(list);
    axios.delete(`/users/${id}`)
  }

  const showConfirm = (item) => {
    confirm({
      title: '您确定要删除该用户吗？',
      icon: <ExclamationCircleOutlined />,
  
      onOk() {
        deleteuser(item.id)
      },
  
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const handleChange = (item) =>{
    console.log(item);
    item.roleState = !item.roleState;
    setDataSource([...dataSource]);
    axios.patch(`/users/${item.id}`,{roleState:item.roleState})
  }
  
  const judgeregiondisabled = (item) =>{
    if(id === 1)
      return false;
    else
      return region !== item.value
  }

  const judgerolesdisabled = (item) =>{
    if(id === 1)
      return false;
    else
      return !(id < item.roleType);
  } 

  return (
    <div>
      <Button type="primary"  style={{marginBottom:'1rem'}} onClick={()=>{
        setVisible(true);
      }}>
        添加用户
      </Button>
      <Modal
        visible={visible}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setVisible(false);
        }}
        onOk={(values) => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
          ref = {ref}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[
              {
                required: true,
                message: '请填写用户名',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[
              {
                required: true,
                message: '请填写密码',
              },
            ]}
          >
            <Input.Password/>
          </Form.Item>
          <Form.Item 
              name="region" 
              label="地区" 
              rules={[
                { 
                  required: !isDisabled,
                  message: '请选择一个地区' }]}>
            <Select
              placeholder="选择一个区域"
              allowClear
              disabled={isDisabled}
            >
              {regionList.map(item =>
                <Option disabled={judgeregiondisabled(item)} key={item.id} value={item.value}>{item.title}</Option>)
              }
            </Select>
          </Form.Item>
          <Form.Item 
              name="roleId" 
              label="角色名称" 
              rules={[
                { 
                  required: true,
                  message: '请选择一个角色' }]}>
            <Select
              placeholder="选择一个角色"
              allowClear
              onChange={(value)=>{
                if(value === 1){      //角色为超级管理员时，不选择区域
                  ref.current.setFieldsValue({   
                    region:''
                  })
                  setIsDisabled(true)
                }
                else{
                  setIsDisabled(false)
                }
              }}
            >
              {roleList.map(item =>
                <Option key={item.id} disabled={judgerolesdisabled(item)} value={item.roleType}>{item.roleName}</Option>)
              }
            </Select>
          </Form.Item>
        </Form>
      </Modal>
      <Table 
        dataSource={filterdatasourece(dataSource)} 
        columns={columns} 
        pagination= {{ pageSize:5 }} 
        rowKey={(item)=>item.id}
      />
    </div>
  )
}
